package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Macross
 * @Type AdminController.java
 * @Desc
 * @date 2019/12/23 12:11
 */
@RestController
@RequestMapping("/admin")
@Api(description = "管理员信息控制器" )
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;

    /**
     * 添加管理员信息
     * @param admin 管理员信息
     * @return
     */
    @PostMapping
    @ApiOperation(value = "添加管理员信息")
    public Result addAdmin(@RequestBody @ApiParam(value = "管理员信息") Admin admin){
        //添加管理员信息
        adminService.add(admin);
        //返回请求结果
        return new Result(true,StatusCode.OK,"添加成功");
    }

    @PostMapping("/login")
    @ApiOperation(value = "管理员登录")
    public Result<String> login(@RequestBody @ApiParam(value = "管理员登录信息") Admin admin){
        if (StringUtils.isNotBlank(admin.getLoginName()) && StringUtils.isNotBlank(admin.getPassword())) {
            Admin loginAdmin = adminService.login(admin.getLoginName(),admin.getPassword());
            if (loginAdmin != null){
                Map<String,Object> params = new HashMap<>(1);
                params.put("roles","admin");
                String token = jwtUtil.createToken(params, loginAdmin.getLoginName(), loginAdmin.getId());
                return new Result<>(true,StatusCode.OK,"登陆成功",token);
            }
            return new Result<>(false,StatusCode.LOGIN_ERROR,"登录名或密码不匹配",null);
        }
        return new Result<>(false,StatusCode.LOGIN_ERROR,"登录名和密码不能为空",null);
    }

    @DeleteMapping("/{adminId}")
    @ApiOperation(value = "删除管理员信息",notes = "删除管理员id对应的管理员信息")
    public Result delete(@PathVariable @ApiParam(value = "管理员ID",required = true) String adminId){
        //判断request中的claims对象是否为null
        if (request.getAttribute("claims") != null) {
            //获取claims对象
            Claims claims = (Claims) request.getAttribute("claims");
            //获取角色信息
            String roles = (String) claims.get("roles");
            //判断角色是否为admin
            if (StringUtils.equals(roles,"admin")) {
                //执行删除管理员操作
                adminService.delete(adminId);
                //返回请求状态
                return new Result(true,StatusCode.OK,"操作成功");
            }
        }
        //返回请求状态
        return new Result(false,StatusCode.ACCESS_ERROR,"没有权限执行操作");
    }
}
